package com.jiangyg.mall.core.support.web;

import com.jiangyg.mall.core.exception.BusinessException;
import com.jiangyg.mall.core.support.restful.Result;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 类描述：接口服务Rest接口异常处理
 *
 * @author jiangyg
 * @version 2.0
 * @date 2019-11-06
 */
@Slf4j
@Order(8)
@RestControllerAdvice
public class RestfulExceptionHandler {

    /**
     * 功能描述：请求方法错误
     *
     * @param ex 异常
     * @return 返回提示信息
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    public Result<Object> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        return Result.error("请求方法不支持！");
    }

    /**
     * 功能描述：Rest接口参数校验异常
     *
     * @param ex 验证异常
     * @return 返回验证信息
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        /*// 获取参数验证错误信息
        final List<ValidationError> errors = new ArrayList<>();
        final BindingResult bind = ex.getBindingResult();
        final List<ObjectError> list = bind.getAllErrors();
        for (ObjectError error : list) {
            // 字段验证错误
            if (error instanceof FieldError) {
                final FieldError fieldError = (FieldError) error;
                errors.add(ValidationError.buildFiledError(fieldError.getField(), fieldError.getDefaultMessage()));
                continue;
            }
            // 对象验证错误
            errors.add(ValidationError.buildObjectError(error.getDefaultMessage()));
        }*/
        // 返回验证错误信息
        return Result.instance("300");
    }

    /**
     * 功能描述：业务异常
     *
     * @param ex 业务异常
     * @return 返回提示信息
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = {BusinessException.class})
    public Result<Object> businessException(Exception ex) {
        return Result.error(ex.getMessage());
    }

    /**
     * 功能描述：其他未知异常
     *
     * @param ex 未知异常
     * @return 返回提示信息
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = {Exception.class})
    public Result<Object> exception(Exception ex) {
        Logger.error(log, () -> "发生未知异常：", ex);
        return Result.error();
    }

}
